import { api } from './client';
import { Admin, Student, Teacher, Course } from '../types';
import { mockAdmin } from './mockData';

// 辅助函数：尝试调用真实API，失败则使用mock
async function tryApiOrMock<T>(
  apiCall: () => Promise<T>,
  mockCall: () => T | Promise<T>
): Promise<T> {
  try {
    return await apiCall();
  } catch (e: any) {
    // 如果是mock标记，直接使用mock
    if (e.isMock || e.message === 'USE_MOCK_DATA') {
      return await mockCall();
    }
    // 如果是401未授权错误，也使用mock（避免跳转到登录页）
    if (e.message === '未登录' || e.message?.includes('401') || e.message?.includes('Unauthorized')) {
      return await mockCall();
    }
    // 其他错误直接抛出
    throw e;
  }
}

export const loginAdmin = (username: string, password: string) => {
  return api<{ token: string; user: Admin }>('/auth/login', {
    method: 'POST',
    body: JSON.stringify({ username, password, role: 'admin' }),
  }).catch((error: any) => {
    if (error.isMock || error.message === 'USE_MOCK_DATA') {
      throw new Error('后端服务不可用，请检查后端是否正在运行');
    }
    throw error;
  });
};

export const getMe = () =>
  tryApiOrMock(
    () => api<Admin>('/admins/me'),
    () => Promise.resolve(mockAdmin)
  );

export const updateProfile = (data: Partial<Admin>) =>
  tryApiOrMock(
    () => api<Admin>('/admins/me', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      // Mock更新：更新mockAdmin对象
      Object.assign(mockAdmin, data);
      return Promise.resolve({ ...mockAdmin });
    }
  );

export const changePassword = (data: { oldPassword: string; newPassword: string }) =>
  tryApiOrMock(
    () => api<{ success: boolean }>('/auth/me/password', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      return Promise.resolve({ success: true });
    }
  );

// 获取所有学生
export const getAllStudents = () =>
  tryApiOrMock(
    () => api<Student[]>('/admins/students'),
    async () => {
      const { mockStudents } = await import('./mockData');
      return Promise.resolve(mockStudents);
    }
  );

// 获取所有教师
export const getAllTeachers = () =>
  tryApiOrMock(
    () => api<Teacher[]>('/admins/teachers'),
    async () => {
      const { mockTeachers } = await import('./mockData');
      return Promise.resolve(mockTeachers);
    }
  );

// 更新学生信息
export const updateStudent = (studentId: string, data: Partial<Student>) =>
  tryApiOrMock(
    () => api<Student>(`/admins/students/${studentId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    async () => {
      const { mockStudents } = await import('./mockData');
      const index = mockStudents.findIndex(s => s.id === studentId);
      if (index !== -1) {
        Object.assign(mockStudents[index], data);
        return Promise.resolve({ ...mockStudents[index] });
      }
      throw new Error('学生不存在');
    }
  );

// 更新教师信息
export const updateTeacher = (teacherId: string, data: Partial<Teacher>) =>
  tryApiOrMock(
    () => api<Teacher>(`/admins/teachers/${teacherId}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    async () => {
      const { mockTeachers } = await import('./mockData');
      const index = mockTeachers.findIndex(t => t.id === teacherId);
      if (index !== -1) {
        Object.assign(mockTeachers[index], data);
        return Promise.resolve({ ...mockTeachers[index] });
      }
      throw new Error('教师不存在');
    }
  );

// 删除学生
export const deleteStudent = (studentId: string) =>
  tryApiOrMock(
    () => api<void>(`/admins/students/${studentId}`, { method: 'DELETE' }),
    async () => {
      const { mockStudents } = await import('./mockData');
      const index = mockStudents.findIndex(s => s.id === studentId);
      if (index !== -1) {
        mockStudents.splice(index, 1);
        return Promise.resolve();
      }
      throw new Error('学生不存在');
    }
  );

// 删除教师
export const deleteTeacher = (teacherId: string) =>
  tryApiOrMock(
    () => api<void>(`/admins/teachers/${teacherId}`, { method: 'DELETE' }),
    async () => {
      const { mockTeachers } = await import('./mockData');
      const index = mockTeachers.findIndex(t => t.id === teacherId);
      if (index !== -1) {
        mockTeachers.splice(index, 1);
        return Promise.resolve();
      }
      throw new Error('教师不存在');
    }
  );

// 创建学生
export const createStudent = (data: Omit<Student, 'id'> & { username: string; password: string }) =>
  tryApiOrMock(
    () => api<Student>('/admins/students', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
    async () => {
      const { mockStudents } = await import('./mockData');
      const newStudent: Student = {
        id: 'student-' + Date.now(),
        ...data,
      };
      mockStudents.push(newStudent);
      return Promise.resolve(newStudent);
    }
  );

// 创建教师
export const createTeacher = (data: Omit<Teacher, 'id'> & { username: string; password: string }) =>
  tryApiOrMock(
    () => api<Teacher>('/admins/teachers', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
    async () => {
      const { mockTeachers } = await import('./mockData');
      const newTeacher: Teacher = {
        id: 'teacher-' + Date.now(),
        ...data,
      };
      mockTeachers.push(newTeacher);
      return Promise.resolve(newTeacher);
    }
  );

// 搜索课程
export const searchCourses = (query: string) =>
  tryApiOrMock(
    () => api<Course[]>(`/admins/courses/search?q=${encodeURIComponent(query)}`),
    async () => {
      const { mockCourses, mockTeachers } = await import('./mockData');
      // 如果没有输入关键词，返回所有课程
      if (!query.trim()) {
        return Promise.resolve(mockCourses);
      }
      
      const lowerQuery = query.toLowerCase().trim();
      
      // 关键字模糊匹配：支持部分匹配
      const filtered = mockCourses.filter(course => {
        // 1. 课程名称模糊匹配（支持关键字）
        const courseNameWords = course.name.toLowerCase().split(/[\s\(\)（）、，,]/);
        const matchCourseName = courseNameWords.some(word => word.includes(lowerQuery)) ||
                               course.name.toLowerCase().includes(lowerQuery);
        
        // 2. 教师姓名模糊匹配
        const matchTeacherName = course.teacherName.toLowerCase().includes(lowerQuery);
        
        // 3. 教师工号匹配
        const matchingTeacher = mockTeachers.find(t => 
          t.account.toLowerCase().includes(lowerQuery) ||
          t.account.toLowerCase() === lowerQuery
        );
        const matchTeacherAccount = matchingTeacher ? course.teacherName === matchingTeacher.name : false;
        
        return matchCourseName || matchTeacherName || matchTeacherAccount;
      });
      
      return Promise.resolve(filtered);
    }
  );

// 课程申请相关类型
export type CourseApplication = {
  id: string;
  name: string;
  teacherName: string;
  teacherAccount: string;
  credit: number;
  capacity: number;
  status: 'pending' | 'approved' | 'rejected';
  applyDate: string;
};

// 获取课程申请列表
export const getCourseApplications = (status?: string) =>
  tryApiOrMock(
    () => {
      const url = status 
        ? `/admins/course-applications?status=${encodeURIComponent(status)}`
        : '/admins/course-applications';
      return api<CourseApplication[]>(url);
    },
    async () => {
      // Mock数据
      return Promise.resolve([
        {
          id: 'app-1',
          name: '人工智能导论',
          teacherName: '张教授',
          teacherAccount: 'T001',
          credit: 3,
          capacity: 50,
          status: 'pending' as const,
          applyDate: '2023-10-05',
        },
      ]);
    }
  );

// 审核课程申请
export const reviewCourseApplication = (applicationId: string, data: { status: 'approved' | 'rejected'; reason?: string }) =>
  tryApiOrMock(
    () => api<{ id: string; status: string }>(`/admins/course-applications/${applicationId}/review`, {
      method: 'POST',
      body: JSON.stringify(data),
    }),
    async () => {
      return Promise.resolve({ id: applicationId, status: data.status });
    }
  );

// 统计数据类型
export type Statistics = {
  totalUsers: number;      // 总用户数（学生+教师）
  totalCourses: number;    // 课程总数（已审核通过的）
  pendingApplications: number; // 待审核申请数
};

// 获取统计数据
export const getStatistics = async (): Promise<Statistics> => {
  try {
    // 并行获取所有数据
    const [students, teachers, courses, pendingApps] = await Promise.all([
      getAllStudents().catch(() => []),
      getAllTeachers().catch(() => []),
      // 获取所有已审核通过的课程
      tryApiOrMock(
        () => api<Course[]>('/courses?approved=true'),
        async () => {
          const { mockCourses } = await import('./mockData');
          return Promise.resolve(mockCourses);
        }
      ).catch(() => []),
      getCourseApplications('pending').catch(() => []),
    ]);

    return {
      totalUsers: (students?.length || 0) + (teachers?.length || 0),
      totalCourses: courses?.length || 0,
      pendingApplications: pendingApps?.length || 0,
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
    // 返回默认值
    return {
      totalUsers: 0,
      totalCourses: 0,
      pendingApplications: 0,
    };
  }
};

